<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
namespace app\portal\controller;

use cmf\controller\UserBaseController;
use think\Db;

class IndexController extends UserBaseController
{

    public function index(){
        $slides=Db::name('slide_item')->where(['slide_id'=>1])->select()->toArray();
        $this->assign('slide',$slides);
        $date=date('Y-m-d',strtotime('+1 day'));

        $list=Db::name('cookbook')->where(['status'=>1])
            ->order('vote_num','desc')->select()->toArray();
        foreach ($list as $k=>$v){
            $where=[
                'cookbook_id'=>$v['id'],
                'eat_date'=>$date
            ];
            $count=Db::name('vote_log')->where($where)->count('id');
            $list[$k]['vote_num']=$count;
        }

        $list=quickSort($list);

        $this->assign('list',$list);

        return $this->fetch(':index');
    }

    public function vote(){
        $id=$this->request->param('id');
        $userId=cmf_get_current_user_id();
        $date=date('Y-m-d',strtotime('+1 day'));

        $where=[ 'user_id'=>$userId,'eat_date'=>$date];
        $count=Db::name('vote_log')->where($where)->count('cookbook_id');

        $where['cookbook_id']=$id;
        $find=Db::name('vote_log')->where($where)->find();
        if($find){
            $this->error('您已经投过了');
        }

        $cookbookCount=Db::name('cookbook')->where(['status'=>1])->count('id');
        $voteNum=ceil($cookbookCount/2);
        if($count<$voteNum){
            $insert=[
                'cookbook_id'=>$id,
                'user_id'=>$userId,
                'create_time'=>time(),
                'eat_date'=>$date
            ];
            Db::name('vote_log')->insert($insert);
            Db::name('cookbook')->where(['id'=>$id])->setInc('vote_num');
            $this->success('投票成功');
        }else{
            $this->error('今天投票次数已用尽');
        }

    }

}
